package com.lime49.lockcrypt.idletimer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;


/**
 * A Timer which monitors user inactivity
 * http://ochafik.free.fr/blog/?p=98
 */
public class IdleTimer {
    private com.lime49.lockcrypt.FrmMainWindow parent;
    private javax.swing.Timer timer;
    private IIdleTimer nativeTimer;
    private int interval = 1000;

    public IdleTimer(com.lime49.lockcrypt.FrmMainWindow parent, int seconds) {
        this.parent = parent;
        String osName = System.getProperty("os.name").toLowerCase();
        try {
            if(osName.startsWith("windows")) {
                nativeTimer = new Win32IdleTimer();
            } else if(osName.startsWith("mac")) {
                throw new Exception("Sorry, AutoLock is not yet available on Mac OS");
            } else {
                nativeTimer = new LinuxIdleTimer();
            }
            timer = new javax.swing.Timer(10000, new RelockActionListener());
            if(seconds > 10) {
                this.interval = (seconds-10)*1000;
            }
        } catch(Exception ex) {
            JOptionPane.showMessageDialog(parent, parent.getLanguage().getString("ERROR")+" #229: "+parent.getLanguage().getString("ERR_STARTIDLETIMER")+":\n"+ex.getLocalizedMessage(), parent.getLanguage().getString("ERROR"), JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public void setInterval(int seconds) {
        if(seconds > 10) {
            this.interval = (seconds-10)*1000;
            timer.start();
        } else {
            timer.stop();
        }
    }

    public void stop() {
        timer.stop();
    }

    class RelockActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if(nativeTimer != null && nativeTimer.getIdleTimeMillis() > interval) {
                parent.relock();
                timer.stop();
            }
        }
    }
}
